package com.woniu.aspect;

import com.alibaba.fastjson.JSONObject;
import com.woniu.entity.Result;
import com.woniu.pojo.Log;
import com.woniu.service.ILogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.NamedThreadLocal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;

/**
 * 日志切面类
 * @author tarnett
 */
@Aspect
@Component
@Slf4j
public class OpreLogAspect {
    @Autowired
    private ILogService logService;
    /** 计算操作消耗时间 */
    private static final ThreadLocal<Long> TIME_THREADLOCAL = new NamedThreadLocal<Long>("CostTime");
    /**
     * 处理请求前执行，记录当前的时间
     */
    @Before("@annotation(opreLog)")
    public void boBefore(OpreLog opreLog) {
        TIME_THREADLOCAL.set(System.currentTimeMillis());
    }

    @Around("@annotation(opreLog)")
    public Object around(ProceedingJoinPoint joinPoint, OpreLog opreLog) throws Throwable {
        try {
            // 执行目标方法
            Result result = (Result) joinPoint.proceed();
            // 记录日志
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = requestAttributes.getRequest();
            Log log = new Log();
            log.setTitle(opreLog.title());
            log.setBusinessType(Integer.parseInt(opreLog.businessType()));
            log.setMethod(joinPoint.getSignature().getName());
            log.setRequestMethod(request.getMethod());
            log.setOperatorType(1);
            UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            log.setOperName(userDetails.getUsername());
            log.setOperUrl(request.getRequestURL().toString());
            log.setOperIp(request.getRemoteAddr());
            log.setOperParam(Arrays.toString(joinPoint.getArgs()));
            log.setJsonResult(JSONObject.toJSONString(result));
            if(result.getCode() == 20000){
                log.setStatus(0);
            }else{
                log.setStatus(1);
            }
            log.setErrorMsg(result.getMessage());
            log.setOperTime(new Date());
            // 设置花费的时间
            log.setCostTime(System.currentTimeMillis() - TIME_THREADLOCAL.get());
            logService.save(log);
            // 返回数据
            return result;
        }finally {
            /*一定要释放ThreadLocal的值，不然可能会内存泄露*/
            TIME_THREADLOCAL.remove();
        }

    }

}
